package command.tv;

import java.util.ArrayList;
import java.util.List;

/**
 * 调用者/请求者（Invoker）:
 * 发送命令的对象，它包含了一个命令对象并能触发命令的执行。调用者并不直接处理请求，而是通过将请求传递给命令对象来实现。
 */
public class Invoker {
    private List<Command> commands = new ArrayList<>();
    private int index;

    public void addCommand(Command command) {
        commands.add(command);
    }

    public void invoke() {
        for (int i = index; i < commands.size(); i++) {
            commands.get(i).execute();
            System.out.println(commands.get(i).toString());
        }
        index = commands.size();
    }

    public void undo() {
        if (index > 0) {
            try {
                commands.get(index - 1).undo();
                index -= 1;
                System.out.println("undo success");
            } catch (UnsupportedOperationException e) {
                index -= 1;
                this.undo();
            }
        } else throw new UnsupportedOperationException("out of range undo");
    }

    public void redo() {
        if (index < commands.size()) {
            commands.get(index).execute();
            index += 1;
            System.out.println("redo success");
        } else throw new UnsupportedOperationException("out of range redo");
    }
}